// src/utils/request.ts
import axios, {
  type AxiosInstance,
  type AxiosRequestConfig,
  type AxiosResponse,
  type AxiosError,
  type InternalAxiosRequestConfig
} from 'axios'

// 定义 API 响应结构
interface ApiResponse<T = any> {
  code: number
  message: string
  data: T
}

// 创建 axios 实例
const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error: AxiosError) => {
    console.error('请求错误:', error)
    showError('请求发送失败')
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse<any>) => {
    const res = response.data
    if (res.code !== 0) {
      showError(res.message || '请求失败')
      return Promise.reject(new Error(res.message || '请求失败'))
    }
    return res
  },
  (error: AxiosError<ApiResponse>) => {
    console.error('响应错误:', error)
    const status = error.response?.status
    const message = error.response?.data?.message || '网络错误，请稍后重试'

    switch (status) {
      case 401:
        showError('未登录或登录已过期')
        window.location.href = '/login'
        break
      case 403:
        showError('权限不足，无法访问')
        break
      case 404:
        showError('请求资源不存在')
        break
      case 500:
        showError('服务器内部错误')
        break
      default:
        showError(message)
    }

    return Promise.reject(error)
  }
)

// 原生错误提示函数
function showError(message: string) {
  alert(message)

  // 或使用 DOM 创建自定义提示（可选）
  // const errorDiv = document.createElement('div')
  // errorDiv.textContent = message
  // errorDiv.style.cssText = 'position:fixed;top:20px;right:20px;background-color:#f56c6c;color:white;padding:10px;border-radius:4px;z-index:1000;'
  // document.body.appendChild(errorDiv)
  // setTimeout(() => {
  //   document.body.removeChild(errorDiv)
  // }, 3000)
}

// 定义请求方法
const request = {
  get<T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> {
    return service.get(url, { params, ...config })
  },

  post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return service.post(url, data, config)
  },

  put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return service.put(url, data, config)
  },

  delete<T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> {
    return service.delete(url, { params, ...config })
  },

  upload<T = any>(url: string, file: File, config?: AxiosRequestConfig): Promise<T> {
    const formData = new FormData()
    formData.append('file', file)
    return service.post(url, formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
      ...config
    })
  },

  download(url: string, params?: any, filename?: string): Promise<void> {
    return service
      .get(url, {
        params,
        responseType: 'blob'
      })
      .then(response => {
        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', filename || '文件下载')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      })
  }
}

export default request
